﻿using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
//using SixLabors.ImageSharp;
//using SixLabors.ImageSharp.Formats.Webp;
//using YougeBookmark.Utilities;

namespace YougeBookmark.Utilities
{
    public class ImageHelper
    {
        private readonly Logger _logger;

        public ImageHelper(Logger logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        //public static void SaveAsWebp(SixLabors.ImageSharp.Image image, string savePath)
        //{
        //    //image.Save(savePath, new WebpEncoder
        //    //{
        //    //    Quality = 80, // 质量参数
        //    //    Method = WebpEncodingMethod.Default
        //    //});

        //    // 创建文件流并自动释放资源
        //    using (var fileStream = File.Create(savePath))
        //    {
        //        image.Save(fileStream, new WebpEncoder
        //        {
        //            Quality = 80,
        //            Method = WebpEncodingMethod.Default
        //        });
        //    }

        //}

        /// <summary>
        /// 保存图片到指定目录（自动生成唯一文件名）
        /// </summary>
        /// <param name="imageData">原始二进制图片数据</param>
        /// <param name="maxWidth">最大宽度（0表示不调整）</param>
        /// <param name="quality">压缩质量（1-100）</param>
        /// <returns>保存后的相对路径（如：/Thumbnails/2023-10/abc.jpg）</returns>
        //public string SaveImage(byte[] imageData, int maxWidth = 800, int quality = 80)
        //{
        //    try
        //    {
        //        using var ms = new MemoryStream(imageData);
        //        using var srcImage = Image.FromStream(ms);

        //        // 创建日期分片目录
        //        var datePath = DateTime.Now.ToString("yyyy-MM");
        //        var fullDir = Path.Combine("Resources", "Thumbnails", datePath);
        //        Directory.CreateDirectory(fullDir);

        //        // 生成唯一文件名（格式优先使用webp）
        //        var fileName = $"{Guid.NewGuid():N}.webp";
        //        var fullPath = Path.Combine(fullDir, fileName);

        //        // 调整尺寸并保存
        //        using var processedImage = ProcessImage(srcImage, maxWidth);
        //        SaveAsWebP(processedImage, fullPath, quality);

        //        return Path.Combine("Thumbnails", datePath, fileName).Replace('\\', '/');
        //    }
        //    catch (ArgumentException ex)
        //    {
        //        _logger.Error("无效的图片数据格式", ex);
        //        throw new InvalidDataException("不支持的图片格式", ex);
        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.Error($"图片保存失败: {ex.Message}", ex);
        //        throw;
        //    }
        //}


        /// <summary>
        /// 保存图片到指定目录（自动生成唯一文件名）
        /// </summary>
        /// <param name="imageData">原始二进制图片数据</param>
        /// <param name="maxWidth">最大宽度（0表示不调整）</param>
        /// <param name="quality">压缩质量（1-100）</param>
        /// <returns>保存后的相对路径（如：/Thumbnails/2023-10/abc.jpg）</returns>
        public string SaveImage(byte[] imageData, int maxWidth = 800, int quality = 80)
        {
            try
            {
                using var ms = new MemoryStream(imageData);
                using var srcImage = Image.FromStream(ms);

                // 创建日期分片目录
                var datePath = DateTime.Now.ToString("yyyy-MM");
                var fullDir = Path.Combine("Resources", "Thumbnails", datePath);
                Directory.CreateDirectory(fullDir);

                // 生成唯一文件名
                var fileName = $"{Guid.NewGuid():N}.jpg";
                var fullPath = Path.Combine(fullDir, fileName);

                // 调整尺寸并保存
                using var processedImage = ProcessImage(srcImage, maxWidth);
                SaveAsJpeg(processedImage, fullPath, quality);

                return Path.Combine("Thumbnails", datePath, fileName).Replace('\\', '/');
            }
            catch (ArgumentException ex)
            {
                _logger.Error("无效的图片数据格式", ex);
                throw new InvalidDataException("不支持的图片格式", ex);
            }
            catch (Exception ex)
            {
                _logger.Error($"图片保存失败: {ex.Message}", ex);
                throw;
            }
        }

        private Image ProcessImage(Image srcImage, int maxWidth)
        {
            if (maxWidth <= 0 || srcImage.Width <= maxWidth)
                return (Image)srcImage.Clone();

            // 按比例计算新高度
            var ratio = (double)maxWidth / srcImage.Width;
            var newHeight = (int)(srcImage.Height * ratio);

            var destImage = new Bitmap(maxWidth, newHeight);
            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                // 填充白色背景（解决透明背景变黑问题）
                graphics.Clear(Color.White);
                graphics.DrawImage(srcImage, 0, 0, maxWidth, newHeight);
            }
            return destImage;
        }

        private void SaveAsJpeg(Image image, string path, int quality)
        {
            var jpegEncoder = GetEncoder(ImageFormat.Jpeg);
            var encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, quality);

            // 自动创建目录
            var dir = Path.GetDirectoryName(path);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            image.Save(path, jpegEncoder, encoderParams);
        }

        private ImageCodecInfo GetEncoder(ImageFormat format)
        {
            var codecs = ImageCodecInfo.GetImageEncoders();
            foreach (var codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                    return codec;
            }
            throw new NotSupportedException("未找到匹配的图片编码器");
        }

        /// <summary>
        /// 图片处理流水线（尺寸调整 + 格式转换）
        /// </summary>
        //private Image ProcessImage(Image srcImage, int maxWidth)
        //{
        //    // 无需调整尺寸的情况
        //    if (maxWidth <= 0 || srcImage.Width <= maxWidth)
        //        return (Image)srcImage.Clone();

        //    // 计算等比缩放高度
        //    var ratio = (double)maxWidth / srcImage.Width;
        //    var newHeight = (int)(srcImage.Height * ratio);

        //    var destImage = new Bitmap(maxWidth, newHeight);
        //    using var g = Graphics.FromImage(destImage);
        //    g.CompositingQuality = CompositingQuality.HighQuality;
        //    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        //    g.DrawImage(srcImage, 0, 0, maxWidth, newHeight);

        //    return destImage;
        //}

        /// <summary>
        /// 高性能保存为WebP格式（需System.Drawing.Common支持）
        /// </summary>
        private void SaveAsWebP(Image image, string path, int quality)
        {
            var encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = new EncoderParameter(
                Encoder.Quality,
                Math.Clamp(quality, 1, 100)
            );

            var encoderInfo = ImageCodecInfo.GetImageEncoders()
                .FirstOrDefault(c => c.FormatID == ImageFormat.Webp.Guid/*ImageFormat.WebP.Guid*/);

            if (encoderInfo == null)
                throw new NotSupportedException("当前系统不支持WebP编码");

            image.Save(path, encoderInfo, encoderParams);
            //创建文件流并自动释放资源

            //var image = SixLabors.ImageSharp.Image.Load(path);

            //using (var fileStream = File.Create(path))
            //{
            //    image.Save(fileStream, new SixLabors.ImageSharp.Formats.Webp.WebpEncoder
            //    {
            //        Quality = 80,
            //        Method = SixLabors.ImageSharp.Formats.Webp.WebpEncodingMethod.Default
            //    });
            //}
        }

        /// <summary>
        /// 替换旧图片文件（原子操作保证数据一致性）
        /// </summary>
        public string ReplaceImage(string oldPath, byte[] newData)
        {
            if (!File.Exists(oldPath))
                return SaveImage(newData);

            try
            {
                var newPath = SaveImage(newData);
                File.Delete(oldPath); // 先保存成功后再删除旧文件
                return newPath;
            }
            catch (Exception ex)
            {
                _logger.Error($"图片替换失败: {ex.Message}", ex);
                throw;
            }
        }
    }
}